import { defineStore } from 'pinia'

export const useLoginStore = defineStore('login', {
  state: () => ({
    userInfo: null,
    isLogin: false
  }),
  
  actions: {
    setUserInfo(info) {
      this.userInfo = info
      this.isLogin = true
      localStorage.setItem('userInfo', JSON.stringify(info))
      localStorage.setItem('isLogin', 'true')
    },
    
    loadFromStorage() {
      const userInfo = localStorage.getItem('userInfo')
      const isLogin = localStorage.getItem('isLogin')
      if (userInfo) this.userInfo = JSON.parse(userInfo)
      if (isLogin === 'true') this.isLogin = true
    },
    
    clearLoginInfo() {
      this.userInfo = null
      this.isLogin = false
      localStorage.removeItem('userInfo')
      localStorage.removeItem('isLogin')
    }
  },
  
  getters: {
    realName: (state) => state.userInfo?.realName || '超级管理员',
    isSuperAdmin: (state) => state.userInfo?.adminType === 1,
    hasPermission: (state) => (requiredRole) => {
      if (requiredRole === 'superAdmin') {
        return state.userInfo?.adminType === 1
      }
      return true
    }
  }
})
